//
//  MyHistory.m
//  Car
//
//  Created by 何晓文 on 15/10/7.
//  Copyright (c) 2015年 朱鸿儒. All rights reserved.
//

#import "MyHistory.h"

@implementation MyHistory

static MyHistory *myHistory;
static FMDatabase *_historyDB;

+ (MyHistory *)shareHistory {
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		if (myHistory == nil) {
			myHistory = [[MyHistory alloc] init];
		}
	});

	return myHistory;
}

- (NSString *)getSqlitePathWithUser:(NSString *)user {
	
	//获取document路径
	NSString *docPath = [NSSearchPathForDirectoriesInDomains(9, 9, 1) lastObject];
	//拼接文件路径
	NSString *filePath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@history.sqlite", user]];
	NSLog(@"%@", filePath);
	return filePath;
}
/**
 *添加收藏
 */
- (void)addHistoryModel:(RecommendModel *)model WithUser:(NSString *)user {
	
	//创建数据库文件
	_historyDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	//链接数据库
	[_historyDB open];
	NSString *slq = [NSString stringWithFormat:@"create table if not exists History (id integer primary key,title TEXT,newsID integer UNIQUE,imageURL TEXT,time TEXT,replycount TEXT,newsURL TEXT);"];
	//创建表
	[_historyDB executeUpdate:slq];
	
	//插入数据
	BOOL done = [_historyDB executeUpdateWithFormat:@"insert into History (title,newsID,imageURL,time,replycount,newsURL) values (%@,%@,%@,%@,%@,%@);",model.title,model.ID, model.smallpic, model.time, model.replycount, model.url];
	if (done) {
		
	}else {

	}
	
}
- (void)deleteHistoryWithUser:(NSString *)user {
	_historyDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	[_historyDB open];
	NSString *slq = [NSString stringWithFormat:@"delete from History"];
	BOOL result = [_historyDB executeUpdate:slq];
	if (result) {
		[ProgressHUD showSuccess:@"删除成功"];
	}else {
		[ProgressHUD showError:@"删除失败"];
	}
	
}


- (NSMutableArray *)extractDataWithUser:(NSString *)user {
	NSMutableArray *array = [NSMutableArray array];
	
	_historyDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	[_historyDB open];
	
	//查询所有音乐收藏数据
	NSString *sql = [NSString stringWithFormat:@"select * from History ORDER BY ID DESC LIMIT 30"];
	FMResultSet *set = [_historyDB executeQuery:sql];
	while (set.next) {
		//将数据库中的blob转化为data
		
		//初始化model接收
		RecommendModel *model = [[RecommendModel alloc] init];
		model.title = [set objectForColumnName:@"title"];
		model.time = [set objectForColumnName:@"time"];
		model.smallpic = [set objectForColumnName:@"imageURL"];
		model.ID = [set objectForColumnName:@"newsID"];
		model.url = [set objectForColumnName:@"newsURL"];
		model.replycount = [set objectForColumnName:@"replycount"];
		
		NSLog(@"%@",model.title);
		[array addObject:model];
	}
	
	return array;
	
}
@end
